<template>
  <view class="goods-page">
    <!-- 头部导航栏 -->
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <text>←</text>
        </view>
        <text class="page-title">筛选结果</text>
        <view class="header-right">
          <image class="header-icon" src="../../static/images/gouwuche.png" @click="navTo('/pages/cart/cart'+`?userAccount=${account_user}`)"/>
        </view>
      </view>
    </view>

    <!-- 筛选条件标签显示 -->
    <view class="filter-tags" v-if="hasActiveFilters">
      <scroll-view class="tags-scroll" scroll-x show-scrollbar="false">
        <view class="tags-list">
          <view class="filter-tag" v-if="filters.priceRange.enabled && filters.priceRange.value">
            <text>价格: {{filters.priceRange.value}}</text>
            <text class="tag-close" @click="removeFilter('priceRange')">×</text>
          </view>
          <view class="filter-tag" v-if="filters.tempRange.enabled && filters.tempRange.value">
            <text>温度: {{filters.tempRange.value}}</text>
            <text class="tag-close" @click="removeFilter('tempRange')">×</text>
          </view>
          <view class="filter-tag" v-if="filters.tempConfig.enabled && filters.tempConfig.value">
            <text>配置: {{filters.tempConfig.value}}</text>
            <text class="tag-close" @click="removeFilter('tempConfig')">×</text>
          </view>
          <view class="filter-tag" v-if="filters.tempScope.enabled">
            <text>温度范围: {{filters.tempScope.value}}℃</text>
            <text class="tag-close" @click="removeFilter('tempScope')">×</text>
          </view>
          <view class="filter-tag" v-if="filters.power.enabled">
            <text>功率: {{filters.power.value}}W</text>
            <text class="tag-close" @click="removeFilter('power')">×</text>
          </view>
          <view class="filter-tag" v-if="filters.heat.enabled">
            <text>消热量: {{filters.heat.value}}kJ</text>
            <text class="tag-close" @click="removeFilter('heat')">×</text>
          </view>
          <view class="filter-tag" v-if="filters.pressure.enabled">
            <text>压强: {{filters.pressure.value}}Pa</text>
            <text class="tag-close" @click="removeFilter('pressure')">×</text>
          </view>
          <view class="clear-all-btn" @click="clearAllFilters">
            <text>清空全部</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-content">
      <view class="result-info">
        <text class="result-count">共找到 {{filteredProducts.length}} 件商品</text>
      </view>

      <!-- 商品瀑布流布局 -->
      <view class="products-waterfall" v-if="filteredProducts.length > 0">
        <view class="product-column">
          <view class="product-item" v-for="(item, index) in leftColumnProducts" :key="'left-' + index" @click="gotoshop(item)">
            <view class="product-image">
              <image :src="getProductImage(item)" mode="aspectFill"/>
            </view>
            <view class="product-content">
              <text class="product-title">{{ item.name_commodity }}</text>
              <text class="product-desc">{{ item.description_commodity }}</text>
              <view class="price-row">
                <view class="current-price">
                  <text class="currency">¥</text>
                  <text class="amount">{{ item.money_commodity }}</text>
                </view>
                <view class="sales-info">
                  <text>已售{{ Math.floor(Math.random() * 1000) + 100 }}件</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <view class="product-column">
          <view class="product-item" v-for="(item, index) in rightColumnProducts" :key="'right-' + index" @click="gotoshop(item)">
            <view class="product-image">
              <image :src="getProductImage(item)" mode="aspectFill"/>
            </view>
            <view class="product-content">
              <text class="product-title">{{ item.name_commodity }}</text>
              <text class="product-desc">{{ item.description_commodity }}</text>
              <view class="price-row">
                <view class="current-price">
                  <text class="currency">¥</text>
                  <text class="amount">{{ item.money_commodity }}</text>
                </view>
                <view class="sales-info">
                  <text>已售{{ Math.floor(Math.random() * 1000) + 100 }}件</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-else>
        <image class="empty-image" src="../../static/images/empty.png" mode="aspectFit"/>
        <text class="empty-text">暂无符合条件的商品</text>
        <button class="back-shop-btn" @click="goBack">返回商城</button>
      </view>
    </view>
  </view>
</template>

<script>
import {_allshopequip} from '@/service/shop.js'

export default {
  data() {
    return {
      account_user: '',
      allProducts: [], // 所有商品
      filteredProducts: [], // 筛选后的商品
      filters: {
        priceRange: { enabled: false, value: '' },
        tempRange: { enabled: false, value: '' },
        tempConfig: { enabled: false, value: '' },
        tempScope: { enabled: false, value: 100 },
        power: { enabled: false, value: 1000 },
        heat: { enabled: false, value: 100 },
        pressure: { enabled: false, value: 50 },
        smartSelect: { enabled: false }
      }
    };
  },
  computed: {
    leftColumnProducts() {
      return this.filteredProducts.filter((_, index) => index % 2 === 0);
    },
    rightColumnProducts() {
      return this.filteredProducts.filter((_, index) => index % 2 === 1);
    },
    hasActiveFilters() {
      return Object.values(this.filters).some(filter => filter.enabled);
    }
  },
  onLoad() {
    const systemInfo = uni.getSystemInfoSync();
    document.documentElement.style.setProperty('--status-bar-height', systemInfo.statusBarHeight + 'px');
    
    // 获取用户信息
    try {
      const value = uni.getStorageSync('userInfo');
      if (value != null) {
        this.account_user = value.accountNum;
      }
    } catch (e) {
      console.error(e);
    }

    // 获取筛选条件
    try {
      const filterConditions = uni.getStorageSync('filterConditions');
      if (filterConditions) {
        this.filters = filterConditions;
        console.log('读取筛选条件:', this.filters);
      }
    } catch (e) {
      console.error('读取筛选条件失败:', e);
    }

    // 加载商品数据
    this.loadProducts();
  },
  methods: {
    // 加载商品数据
    async loadProducts() {
      try {
        let res = await _allshopequip();
        this.allProducts = res.data;
        console.log('所有商品:', this.allProducts);
        
        // 应用筛选
        this.applyFilters();
      } catch (e) {
        console.error('加载商品失败:', e);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      }
    },

    // 应用筛选条件
    applyFilters() {
      this.filteredProducts = this.allProducts.filter(product => {
        let match = true;

        // 价格区间筛选
        if (this.filters.priceRange.enabled && this.filters.priceRange.value) {
          const price = parseFloat(product.money_commodity);
          const range = this.filters.priceRange.value;
          
          if (range === '0-1000') {
            match = match && (price >= 0 && price <= 1000);
          } else if (range === '1000-2000') {
            match = match && (price > 1000 && price <= 2000);
          } else if (range === '2000-3000') {
            match = match && (price > 2000 && price <= 3000);
          } else if (range === '3000以上') {
            match = match && (price > 3000);
          }
        }

        // 温度区间筛选（基于商品名称关键词）
        if (this.filters.tempRange.enabled && this.filters.tempRange.value) {
          const name = product.name_commodity || '';
          const range = this.filters.tempRange.value;
          
          if (range === '0-100℃') {
            match = match && (name.includes('低温') || name.includes('冷'));
          } else if (range === '100-200℃') {
            match = match && (name.includes('中温') || name.includes('温'));
          } else if (range === '200-300℃') {
            match = match && (name.includes('高温') || name.includes('热'));
          } else if (range === '300℃以上') {
            match = match && (name.includes('加热') || name.includes('炉'));
          }
        }

        // 温度配置长度筛选
        if (this.filters.tempConfig.enabled && this.filters.tempConfig.value) {
          const desc = product.description_commodity || '';
          const config = this.filters.tempConfig.value;
          
          if (config === '短') {
            match = match && (desc.includes('小型') || desc.includes('迷你'));
          } else if (config === '中') {
            match = match && (desc.includes('中型') || desc.includes('标准'));
          } else if (config === '长') {
            match = match && (desc.includes('大型') || desc.includes('加长'));
          }
        }

        // 智能选择：如果启用，优先推荐加热设备
        if (this.filters.smartSelect.enabled) {
          const name = product.name_commodity || '';
          if (name.includes('加热') || name.includes('搅拌') || name.includes('粉碎')) {
            // 智能推荐相关产品
          }
        }

        return match;
      });

      console.log('筛选后商品数量:', this.filteredProducts.length);
    },

    // 移除单个筛选条件
    removeFilter(filterKey) {
      this.filters[filterKey].enabled = false;
      if (this.filters[filterKey].value !== undefined) {
        this.filters[filterKey].value = '';
      }
      this.applyFilters();
    },

    // 清空所有筛选条件
    clearAllFilters() {
      this.filters = {
        priceRange: { enabled: false, value: '' },
        tempRange: { enabled: false, value: '' },
        tempConfig: { enabled: false, value: '' },
        tempScope: { enabled: false, value: 100 },
        power: { enabled: false, value: 1000 },
        heat: { enabled: false, value: 100 },
        pressure: { enabled: false, value: 50 },
        smartSelect: { enabled: false }
      };
      this.applyFilters();
    },

    // 根据商品名称获取对应的图片路径
    getProductImage(item) {
      const productName = item.name_commodity || '';

      const productImageMap = {
        '箱式加热炉': '../../static/images/xiangshijiarelu.jpg',
        '柜式加热炉': '../../static/images/guishijiarelu.jpg',
        '搅拌器': '../../static/images/jiaobanji.jpg',
        '家用搅拌器': '../../static/images/shiyanyongfensuiji.jpg',
        '锐牌粉碎机': '../../static/images/ruipaijiaobanji.jpg',
        '粉碎机': '../../static/images/fensuiji.jpg'
      };

      for (const productType in productImageMap) {
        if (productName.includes(productType)) {
          return productImageMap[productType];
        }
      }

      const imageUrl = item.image;
      if (typeof imageUrl === 'string' && imageUrl) {
        return imageUrl;
      }
      return '../../static/images/jiarelu.jpg';
    },

    // 跳转到商品详情
    gotoshop(data) {
      console.log('🏪 商品点击，原始数据:', data);
      
      let productImage = this.getProductImage(data);
      console.log('🖼️ 获取的商品图片:', productImage);

      if (typeof productImage !== 'string') {
        console.warn('⚠️ goods.vue: productImage 不是字符串，使用默认图片', productImage);
        productImage = '../../static/images/jiarelu.jpg';
      }

      const productData = {
        ...data,
        productImage: productImage
      };

      console.log('💾 存储到本地的商品数据:', productData);
      uni.setStorageSync('shoptoproduct', productData);
      
      uni.navigateTo({
        url: '/pages/product/product'
      });
    },

    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 页面跳转
    navTo(url) {
      uni.navigateTo({
        url: url
      });
    }
  }
}
</script>

<style lang="scss">
/* 页面整体布局 */
.goods-page {
  background: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 100rpx;
  padding-top: calc(var(--status-bar-height, 44px) + 60px);
}

/* 头部导航栏 */
.header {
  background: white;
  padding: 15px;
  padding-top: calc(var(--status-bar-height, 44px) + 15px);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  width: 100%;
  z-index: 101;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);

  .header-content {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .back-btn {
      width: 70rpx;
      height: 70rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 48rpx;
      color: #333;
      cursor: pointer;

      &:active {
        opacity: 0.6;
      }
    }

    .page-title {
      flex: 1;
      text-align: center;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }

    .header-right {
      width: 70rpx;
      display: flex;
      justify-content: flex-end;

      .header-icon {
        width: 45rpx;
        height: 40rpx;
        cursor: pointer;

        &:active {
          transform: scale(0.9);
        }
      }
    }
  }
}

/* 筛选条件标签 */
.filter-tags {
  background: white;
  padding: 20rpx 0;
  margin-bottom: 20rpx;

  .tags-scroll {
    white-space: nowrap;

    &::-webkit-scrollbar {
      display: none;
    }

    .tags-list {
      display: inline-flex;
      gap: 20rpx;
      padding: 0 30rpx;

      .filter-tag {
        display: inline-flex;
        align-items: center;
        gap: 10rpx;
        padding: 12rpx 24rpx;
        background: #e6f7ff;
        border: 2rpx solid #1890ff;
        border-radius: 40rpx;
        font-size: 26rpx;
        color: #1890ff;
        white-space: nowrap;

        .tag-close {
          font-size: 32rpx;
          font-weight: bold;
          cursor: pointer;

          &:active {
            opacity: 0.6;
          }
        }
      }

      .clear-all-btn {
        display: inline-flex;
        align-items: center;
        padding: 12rpx 24rpx;
        background: #f8f9fa;
        border: 2rpx solid #ddd;
        border-radius: 40rpx;
        font-size: 26rpx;
        color: #666;
        white-space: nowrap;
        cursor: pointer;

        &:active {
          background: #e9ecef;
        }
      }
    }
  }
}

/* 商品内容区域 */
.goods-content {
  padding: 0 20rpx;

  .result-info {
    padding: 30rpx 10rpx 20rpx;

    .result-count {
      font-size: 28rpx;
      color: #666;
    }
  }

  /* 商品瀑布流布局 */
  .products-waterfall {
    display: flex;
    gap: 20rpx;
    background: transparent;

    .product-column {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 20rpx;

      .product-item {
        background-color: white;
        border-radius: 12rpx;
        overflow: hidden;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
        transition: transform 0.2s ease;

        &:active {
          transform: scale(0.98);
        }

        .product-image {
          position: relative;
          width: 100%;
          padding-bottom: 100%;
          height: 0;

          image {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .product-content {
          padding: 20rpx;

          .product-title {
            font-size: 28rpx;
            color: #333;
            font-weight: 500;
            line-height: 1.4;
            margin-bottom: 10rpx;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }

          .product-desc {
            font-size: 24rpx;
            color: #999;
            margin-bottom: 15rpx;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }

          .price-row {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .current-price {
              display: flex;
              align-items: baseline;

              .currency {
                font-size: 24rpx;
                color: #ff4757;
                margin-right: 4rpx;
              }

              .amount {
                font-size: 32rpx;
                color: #ff4757;
                font-weight: bold;
              }
            }

            .sales-info {
              font-size: 20rpx;
              color: #999;
            }
          }
        }
      }
    }
  }

  /* 空状态 */
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 200rpx 0;

    .empty-image {
      width: 300rpx;
      height: 300rpx;
      margin-bottom: 40rpx;
      opacity: 0.6;
    }

    .empty-text {
      font-size: 30rpx;
      color: #999;
      margin-bottom: 60rpx;
    }

    .back-shop-btn {
      padding: 24rpx 80rpx;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-radius: 50rpx;
      font-size: 30rpx;
      border: none;

      &::after {
        border: none;
      }

      &:active {
        opacity: 0.8;
      }
    }
  }
}
</style>
